package org.unt.genlogic;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Appender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

public class Logs {

	private static Logger log = Logger.getLogger("???");

	public void runtimeLog4JConfiguration(String filename, List loggerLevels) throws IOException {

		// Daily rolling file appender
		PatternLayout layout = new PatternLayout("%5p %d{HH:mm:ss,SSS} %F:%L -->> %m%n");
		String datePattern = "'.'yyyy-MM-dd";

		Logger rootLogger = Logger.getRootLogger();

		DailyRollingFileAppender appender = null;

		appender = new DailyRollingFileAppender(layout, filename, datePattern);
		appender.setName("ventesBatchAppender");

		rootLogger.addAppender(appender);
		rootLogger.setLevel(Level.INFO);

		Enumeration enu = rootLogger.getAllAppenders();
		while (enu.hasMoreElements()) {

			Appender app = (Appender) enu.nextElement();
			String name = app.getName();

			if (!"ventesBatchAppender".equals(name) && !"stdout".equals(name)) {
				rootLogger.removeAppender(name);
				log.info("Appender removed " + name);
			} else {
				log.info("Appender okay " + name);
			}
		}

		for (Iterator iterator = loggerLevels.iterator(); iterator.hasNext();) {

			LoggerLevel loggerLevel = (LoggerLevel) iterator.next();
			Logger loggerObj = Logger.getLogger(loggerLevel.getLogger());

			if ("DEBUG".equals(loggerLevel.getLevel())) {
				loggerObj.setLevel(Level.DEBUG);
			} else if ("INFO".equals(loggerLevel.getLevel())) {
				loggerObj.setLevel(Level.INFO);
			} else if ("WARN".equals(loggerLevel.getLevel())) {
				loggerObj.setLevel(Level.WARN);
			} else if ("ERROR".equals(loggerLevel.getLevel())) {
				loggerObj.setLevel(Level.ERROR);
			} else if ("FATAL".equals(loggerLevel.getLevel())) {
				loggerObj.setLevel(Level.FATAL);
			}

			log.info("Logger " + loggerLevel.getLogger() + " set to " + loggerLevel.getLevel());
		}
	}

	public class LoggerLevel {

		private String logger;
		private String level;

		public String getLogger() {
			return logger;
		}

		public void setLogger(String logger) {
			this.logger = logger;
		}

		public String getLevel() {
			return level;
		}

		public void setLevel(String level) {
			this.level = level;
		}

	}
}
